import {useState} from "react";
import storage from "./firebase";
import {ref, uploadBytesResumable, getDownloadURL, getStorage, uploadBytes} from "firebase/storage";
import {initializeApp} from "firebase/app";
import {Button, Modal, Upload, UploadFile, UploadProps} from "antd";
import {UploadOutlined} from "@ant-design/icons";
import {RcFile} from "antd/es/upload";

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });
const App = (props) => {
    const {setUrl, initValue} = props;
    // State to store uploaded file
    var dd = [];
    if (typeof initValue != "undefined")
        initValue.forEach((v, i) => {
            dd.push({
                uid: i,
                name: i + v.indexOf("video") != -1 ? "Video" : "Image",
                status: 'done',
                url: v,
            });
        });

    const [file, setFile] = useState<UploadFile[]>(dd);
    // progress
    const [percent, setPercent] = useState(0);
    const [finishCnt, setFinishCnt] = useState(0);

    // Handle file upload event and update state

    const handleUpload: UploadProps['customRequest'] = async ({file, onError, onProgress, onSuccess}) => {
        try {
            var fileName = (file.uid + "_" + file.type).replace(new RegExp("/", 'g'), "");
            const storageRef = ref(storage, `/images3/${fileName}`);
            // const BlobFile = rcFileToBlob(file)
            // progress can be paused and resumed. It also exposes progress updates.
            // Receives the storage reference and the file to upload.
            // const uploadTask = uploadBytesResumable(storageRef, file);
            //
            // uploadBytes(storageRef, file).then((snapshot) => {
            //     console.log(snapshot);
            // });
            const uploadTask = uploadBytesResumable(storageRef, file);
            uploadTask.on('state_changed',
                (snapshot) => {
                    // Observe state change events such as progress, pause, and resume
                    // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    switch (snapshot.state) {
                        case 'paused':
                            console.log('Upload is paused');
                            break;
                        case 'running':
                            console.log('Upload is running');
                            break;
                    }
                },
                (error) => {

                    console.log("0000", error)
                },
                () => {
                    // Handle successful uploads on complete
                    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
                    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                        console.log('File available at',uploadTask.snapshot, downloadURL);
                        onSuccess?.({
                            ...file,
                            downloadURL
                        })

                        setUrl(downloadURL);
                    });
                }
            );

            // uploadTask.on(
            //     "state_changed",
            //     (snapshot) => {
            //         console.log(8888,snapshot.state)
            //         const percent = Math.round(
            //             (snapshot.bytesTransferred / snapshot.totalBytes) * 100
            //         );
            //         // update progress
            //         onProgress?.({percent});
            //     },
            //     (err) => {
            //         onError?.(err);
            //         console.log(err)
            //     },
            //     () => {
            //         // download url
            //         getDownloadURL(uploadTask.snapshot.ref).then((url) => {
            //             onSuccess?.({
            //                 ...file,
            //                 url
            //             });
            //         });
            //     }
            // );
        } catch (error) {
            console.log(error);

        }
    };


    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const handleCancel = () => setPreviewOpen(false);
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    return (
        <>
            <Upload
                // fileList={file}
                defaultFileList={dd}
                listType="picture-card"
                onChange={({file, fileList}) => {
                    setFile(fileList);
                }}
                multiple
                customRequest={handleUpload}
                onPreview={handlePreview}
            >
                {file.length >= 500 ? null : <Button icon={<UploadOutlined/>}>Upload</Button>}

            </Upload>
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
                {
                    previewImage.indexOf("video") != -1 ? <video controls style={{width: '100%'}}>
                        <source src={previewImage} type="video/mp4"/>
                    </video> : <img alt="example" style={{width: '100%'}} src={previewImage}/>
                }

            </Modal>
        </>
    );
}

export default App;